<template>
  <main-content title="优惠券批次">
    <template #search-bar>
      <SearchBar inline>
        <template #normal>
          <el-form-item label="批次ID">
            <el-input
              v-model="searchForm.batchId"
              clearable
              placeholder="请输入批次ID"
            />
          </el-form-item>
          <el-form-item label="优惠券ID">
            <el-input
              v-model="searchForm.couponDefineId"
              clearable
              placeholder="请输入优惠券ID"
            />
          </el-form-item>
          <el-form-item label="批次状态">
            <el-select
              v-model="searchForm.batchStatus"
              placeholder="请选择批次状态"
              clearable
            >
              <el-option
                label="启用"
                :value="1"
              />
              <el-option
                label="禁用"
                :value="0"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="审核状态">
            <el-select
              v-model="searchForm.verifyStatus"
              placeholder="请选择审核状态"
              clearable
            >
              <el-option
                label="待审核"
                :value="0"
              />
              <el-option
                label="审核通过"
                :value="1"
              />
              <el-option
                label="审核拒绝"
                :value="2"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="优惠券名称">
            <el-input
              v-model="searchForm.couponName"
              clearable
              placeholder="请输入优惠券名称"
            />
          </el-form-item>
          <el-form-item label="批次名称">
            <el-input
              v-model="searchForm.couponBatchName"
              clearable
              placeholder="请输入批次名称"
            />
          </el-form-item>
        </template>
        <template #toolbar>
          <el-form-item>
            <el-button
              type="primary"
              @click="research"
            >
              查询
            </el-button>
            <el-button
              type="primary"
              icon="Plus"
              @click="toCreate"
            >
              新增批次
            </el-button>
          </el-form-item>
        </template>
      </SearchBar>
    </template>

    <LayoutTable
      ref="tableRef"
      url="merchant/coupon/pageCouponBatch"
      :param="searchForm"
    >
      <el-table-column
        label="批次ID"
        width="100"
        prop="id"
      />
      <el-table-column
        label="批次名称"
        min-width="140"
        prop="couponBatchName"
      />
      <el-table-column
        label="批次状态"
        width="120"
      >
        <template #default="props">
          <el-switch
            v-model="props.row.batchStatus"
            inline-prompt
            active-text="启用"
            inactive-text="禁用"
            :active-value="1"
            :inactive-value="0"
            :before-change="() => handleStatusChange(props.row)"
          />
        </template>
      </el-table-column>

      <el-table-column
        label="优惠券数量/领取量/使用量"
        width="210"
      >
        <template #default="{row}">
          {{ row?.couponTotalNum ?? '0' }} / {{ row?.couponReceiveNum ?? '0' }} / {{ row?.couponUseNum ?? '0' }}
        </template>
      </el-table-column>
      
      <el-table-column
        label="使用率"
        width="100"
        prop="usedRate"
      >
        <template #default="{row}">
          {{ (row?.usedRate ?? 0) + '%' }}
        </template>
      </el-table-column>

      <el-table-column
        label="审核状态"
        width="150px"
      >
        <template #default="{row}">
          <div class="verify-status-column">
            <el-tag v-if="row.verifyStatus === 0">
              待审核
            </el-tag>
            <el-tag
              v-if="row.verifyStatus === 1"
              type="success"
            >
              通过
            </el-tag>
            <el-tag
              v-if="row.verifyStatus === 2"
              type="danger"
            >
              拒绝
            </el-tag>

            <el-tooltip
              v-if="row.verifyStatus === 2"
              effect="dark"
              :content="row.remark"
              placement="top"
              class="remark"
            >
              <el-icon>
                <Tickets />
              </el-icon>
            </el-tooltip>
          </div>
        </template>
      </el-table-column>

      <el-table-column
        label="审核时间"
        width="210"
      >
        <template #default="props">
          {{ formatTime(props.row.verifyTime) }}
        </template>
      </el-table-column>

      <el-table-column
        label="优惠券ID"
        width="100"
        prop="couponDefineId"
      />

      <el-table-column
        label="优惠券名称"
        min-width="140"
        prop="couponName"
      />

      <el-table-column
        label="创建人"
        width="140"
        prop="createUserName"
      />
      
      <el-table-column
        label="更新时间"
        width="180"
      >
        <template #default="{row}">
          {{ formatTime(row.updateTime) }}
        </template>
      </el-table-column>

      <el-table-column
        label="操作"
        fixed="right"
        width="180"
      >
        <template #default="props">
          <el-button
            type="primary"
            link
            @click="toEdit(props.row)"
          >
            编辑
          </el-button>
          <el-button
            v-if="props.row.batchStatus === 1 && props.row.verifyStatus === 1"
            type="primary"
            link
            @click="exportCoupon(props.row)"
          >
            导出券码
          </el-button>

          <el-button
            type="danger"
            link
            @click="_deleteCouponBatch(props.row)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </LayoutTable>
  </main-content>

  <export-data
    v-model:show-dialog="isShowExportDialog"
    :export-type="exportForm.beanName"
    :title="exportForm.title"
    :search-data="{
      batchId: exportForm.batchId
    }"
  />
</template>

<script setup lang="ts">
import type { ICouponBatchManageRow } from "@/api/modules/marketingTool";
import moment from "moment";
import { deleteCouponBatch, updateCouponBatchStatus } from "@/api/marketingTool"


const router = useRouter()

const searchForm = reactive({
  batchId: "",
  couponDefineId: "",
  couponDefineName: "",
  couponType: "",
  batchStatus: "",
  couponBatchName: "",
  couponName: "",
  verifyStatus: null,
})

const tableRef = ref();

const research = () => {
  tableRef.value.research();
}

const currentRow = ref();

// 新增
const toCreate = () => {
  console.log("新增！！！")
  router.push({
    path: 'coupon_batch_manage/create'
  })
}

// 优惠券批次状态切换
const handleStatusChange: (row: ICouponBatchManageRow) => Promise<boolean> = (row) => {
  return new Promise<boolean>((resolve) => {
    if (row.batchStatus === 1) {
      ElMessageBox.confirm("确认禁用该批次吗？", "提示").then(() => {
        updateCouponBatchStatus({
          id: row.id,
          status: 0 // 批次当前为启用 即将切换为禁用0 禁用 0 启用 1
        }).then(rs => {
          if (rs.code === 200) {
            resolve(true)
          } else {
            resolve(false)
          }
        })
      })
    } else {
      updateCouponBatchStatus({
        id: row.id,
        status: 1  // 批次当前为禁用 即将切换为启用1 禁用 0 启用 1
      }).then(rs => {
        if (rs.code === 200) {
          // 批次当前为禁用（0）时，切换为启用（1）
          ElMessage.success("优惠券批次已提交审核,请耐心等待")
          // 提交审核记录，但是仍然不更改状态 resolve false。
          resolve(false)
          research()
        } else {
          resolve(false)
        }
      })
    }
  }).catch(e => {
    console.log(e)
    return Promise.resolve(false)
  })
}

// 领取时间
const formatTime = (timestamp: number) => {
  return timestamp ? moment(timestamp).format("YYYY.MM.DD HH:mm:ss") : ''
}

// 编辑
const toEdit = (row: ICouponBatchManageRow) => {
  console.log("编辑！！！")
  // if (row.verifyStatus === 1) {
  //   ElMessage.warning("当前批次已通过审核，不可编辑")
  //   return
  // }

  router.push({
    path: 'coupon_batch_manage/edit',
    query: {
      id: row.id
    }
  })
}

// 导出领取明细
const isShowExportDialog = ref(false);
const exportForm = ref({
  beanName: "couponInfoExport", 
  title: "",
  batchId: -1,
})
const exportCoupon = (row: ICouponBatchManageRow) => {
  currentRow.value = row;
  exportForm.value.title = `导出批次券码${row.id}`;
  exportForm.value.batchId = row.id;
  isShowExportDialog.value = true
}

// 删除
const _deleteCouponBatch = (row: ICouponBatchManageRow) => {
  if (row.batchStatus === 1) {
    ElMessage.warning("当前批次已启用，不能删除")
    return
  }
  ElMessageBox.confirm("确认删除？", "提示").then(async () => {
    const rs = await deleteCouponBatch({ id: row.id })
    if (rs.code === 200) {
      ElMessage.success("删除成功")
      research()
    }
  }).catch(() => {
    void 0
  })
}
</script>

<style scoped lang="scss">
.statistics {
  margin-bottom: 18px;
  font-size: 14px;
  color: #333;

  .highlight {
    font-size: 16px;
    color: var(--el-color-primary);
  }
}

.outof-claim-time-range {
  color: #999;
}

.verify-status-column {
  display: flex;
  align-items: center;
 
  :deep(.el-icon) {
    margin-left: 10px;
  }
}
</style>